<template>
  <!-- 导航栏 -->
  <Navbar />
  
  <div class="order-list-container">
    <div class="container">
      <div class="page-header">
        <h2><i class="fas fa-file-alt"></i> 我的订单</h2>
      </div>

      <div class="order-filters">
        <div class="filter-tabs">
          <button 
            v-for="tab in tabs"
            :key="tab.value"
            class="filter-tab"
            :class="{ active: activeTab === tab.value }"
            @click="changeTab(tab.value)"
          >
            {{ tab.label }}
          </button>
        </div>
      </div>

      <div v-if="loading" class="loading-section">
        <div v-for="n in 3" :key="n" class="order-skeleton">
          <div class="skeleton-header"></div>
          <div class="skeleton-content"></div>
          <div class="skeleton-actions"></div>
        </div>
      </div>

      <div v-else-if="filteredOrders.length === 0" class="empty-state">
        <div class="empty-icon">
          <i class="fas fa-file-alt"></i>
        </div>
        <h3>{{ activeTab === 'all' ? '暂无订单' : '暂无' + getTabLabel(activeTab) + '订单' }}</h3>
        <p>{{ activeTab === 'all' ? '快去选购心仪的商品吧' : '去看看其他订单吧' }}</p>
        <button class="btn btn-primary" @click="$router.push('/products')">
          <i class="fas fa-box-open"></i>
          去购物
        </button>
      </div>

      <div v-else class="orders-list">
        <div 
          v-for="order in filteredOrders" 
          :key="order.orderId"
          class="order-card"
        >
          <div class="order-header">
            <div class="order-info">
              <span class="order-number">订单号: {{ order.orderId }}</span>
              <span class="order-date">{{ formatDate(order.purchaseTime || order.orderDate) }}</span>
            </div>
            <div class="order-status">
              <span 
                class="status-badge"
                :class="getStatusClass(order.orderStatus)"
              >
                {{ getStatusText(order.orderStatus) }}
              </span>
            </div>
          </div>

          <div class="order-content" @click="goToOrderDetail(order.orderId)">
            <div class="order-summary">
              <div class="summary-item">
                <i class="fas fa-dollar-sign"></i>
                <span class="label">订单总额:</span>
                <span class="value">¥{{ formatPrice(order.totalAmount) }}</span>
              </div>
              <div class="summary-item">
                <i class="fas fa-credit-card"></i>
                <span class="label">支付方式:</span>
                <span class="value">{{ order.paymentMethod || '在线支付' }}</span>
              </div>
              <div class="summary-item">
                <i class="fas fa-map-marker-alt"></i>
                <span class="label">收货地址:</span>
                <span class="value">{{ order.shippingAddress || '暂无地址' }}</span>
              </div>
              <div class="summary-item">
                <i class="fas fa-phone"></i>
                <span class="label">联系方式:</span>
                <span class="value">{{ order.contactPhone || '暂无' }}</span>
              </div>
            </div>
          </div>

          <div class="order-actions">
            <button 
              v-if="order.orderStatus === 'pending'"
              class="btn btn-primary btn-sm"
              @click="payOrder(order.orderId)"
            >
              <i class="fas fa-credit-card"></i>
              去支付
            </button>
            <button 
              v-if="order.orderStatus === 'shipped'"
              class="btn btn-success btn-sm"
              @click="confirmReceive(order.orderId)"
            >
              <i class="fas fa-check"></i>
              确认收货
            </button>
            <button 
              v-if="canCancel(order.orderStatus)"
              class="btn btn-danger btn-sm"
              @click="cancelOrder(order.orderId)"
            >
              <i class="fas fa-times"></i>
              取消订单
            </button>
            <button 
              class="btn btn-secondary btn-sm"
              @click="goToOrderDetail(order.orderId)"
            >
              <i class="fas fa-eye"></i>
              查看详情
            </button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section" v-if="totalPages > 1">
        <div class="pagination">
          <button 
            class="page-btn"
            :disabled="currentPage <= 1"
            @click="changePage(currentPage - 1)"
          >
            <i class="fas fa-chevron-left"></i>
          </button>
          
          <button 
            v-for="page in visiblePages"
            :key="page"
            class="page-btn"
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
          >
            {{ page }}
          </button>
          
          <button 
            class="page-btn"
            :disabled="currentPage >= totalPages"
            @click="changePage(currentPage + 1)"
          >
            <i class="fas fa-chevron-right"></i>
          </button>
        </div>
        
        <div class="pagination-info">
          共 {{ totalOrders }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
        </div>
      </div>
    </div>
    
    <!-- 浮动购物车 -->
    <FloatingCart />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { orderAPI } from '@/api'
import Navbar from '@/components/Navbar.vue'
import FloatingCart from '@/components/FloatingCart.vue'
import { message, confirm, feedback } from '@/utils/message'

export default {
  name: 'OrderListView',
  components: {
    Navbar,
    FloatingCart
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    
    const loading = ref(false)
    const orders = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const activeTab = ref('all')
    
    const tabs = [
      { label: '全部', value: 'all' },
      { label: '待支付', value: 'pending' },
      { label: '已支付', value: 'paid' },
      { label: '已发货', value: 'shipped' },
      { label: '已完成', value: 'completed' },
      { label: '已取消', value: 'cancelled' }
    ]
    
    const filteredOrders = computed(() => {
      if (activeTab.value === 'all') {
        return orders.value
      }
      return orders.value.filter(order => order.orderStatus === activeTab.value)
    })
    
    const totalOrders = computed(() => filteredOrders.value.length)
    const totalPages = computed(() => Math.ceil(totalOrders.value / pageSize.value))
    
    const visiblePages = computed(() => {
      const total = totalPages.value
      const current = currentPage.value
      const pages = []
      
      if (total <= 7) {
        for (let i = 1; i <= total; i++) {
          pages.push(i)
        }
      } else {
        if (current <= 4) {
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        } else if (current >= total - 3) {
          pages.push(1)
          pages.push('...')
          for (let i = total - 4; i <= total; i++) {
            pages.push(i)
          }
        } else {
          pages.push(1)
          pages.push('...')
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i)
          }
          pages.push('...')
          pages.push(total)
        }
      }
      
      return pages
    })
    
    const fetchOrders = async () => {
      try {
        loading.value = true
        
        // 获取当前用户信息
        let user = store.state.user
        
        // 如果store中没有用户信息，尝试从localStorage获取
        if (!user) {
          const userData = localStorage.getItem('user')
          if (userData) {
            user = JSON.parse(userData)
            store.commit('setUser', user)
          }
        }
        
        if (!user || !user.userId) {
          message.warning('请先登录')
          router.push('/login')
          return
        }
        
        console.log('正在获取用户订单，用户ID:', user.userId)
        const response = await orderAPI.getUserOrders(user.userId)
        
        // 处理不同的响应格式
        let orderList = []
        if (response.orders) {
          orderList = response.orders
        } else if (response.data) {
          orderList = Array.isArray(response.data) ? response.data : [response.data]
        } else if (Array.isArray(response)) {
          orderList = response
        }
        
        // 按时间倒序排列
        orders.value = orderList.sort((a, b) => {
          const timeA = new Date(a.purchaseTime || a.orderDate || 0)
          const timeB = new Date(b.purchaseTime || b.orderDate || 0)
          return timeB - timeA
        })
        
      } catch (error) {
        console.error('获取订单列表失败:', error)
        message.error('获取订单列表失败')
        orders.value = []
      } finally {
        loading.value = false
      }
    }

    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待支付',
        'paid': '已支付',
        'shipped': '已发货',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知状态'
    }
    
    const getStatusClass = (status) => {
      const classMap = {
        'pending': 'status-pending',
        'paid': 'status-paid',
        'shipped': 'status-shipped',
        'completed': 'status-completed',
        'cancelled': 'status-cancelled'
      }
      return classMap[status] || 'status-unknown'
    }
    
    const getTabLabel = (tabValue) => {
      const tab = tabs.find(t => t.value === tabValue)
      return tab ? tab.label : ''
    }
    
    const canCancel = (status) => {
      return ['pending', 'paid'].includes(status)
    }
    
    const changeTab = (tab) => {
      activeTab.value = tab
      currentPage.value = 1
    }
    
    const changePage = (page) => {
      if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page
      }
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return '未知时间'
      try {
        const date = new Date(dateString)
        return date.toLocaleString('zh-CN')
      } catch (error) {
        return '未知时间'
      }
    }
    
    const formatPrice = (price) => {
      return parseFloat(price || 0).toFixed(2)
    }
    
    const goToOrderDetail = (orderId) => {
      router.push(`/order/${orderId}`)
    }
    
    const payOrder = async (orderId) => {
      try {
        // 这里应该调用支付API
        message.info('跳转到支付页面...')
        // 支付成功后刷新订单列表
        await fetchOrders()
      } catch (error) {
        console.error('支付失败:', error)
        message.error('支付失败，请重试')
      }
    }
    
    const confirmReceive = async (orderId) => {
      try {
        await confirm.warning('确认收货', '确认收货后订单将完成，确定要确认收货吗？')
        await orderAPI.updateOrderStatus(orderId, 'completed')
        message.success('确认收货成功')
        await fetchOrders()
      } catch (error) {
        if (error === 'cancel') return // 用户取消
        console.error('确认收货失败:', error)
        message.error('确认收货失败，请重试')
      }
    }
    
    const cancelOrder = async (orderId) => {
      try {
        await confirm.warning('取消订单', '确定要取消这个订单吗？')
        await orderAPI.updateOrderStatus(orderId, 'cancelled')
        message.success('订单已取消')
        await fetchOrders()
      } catch (error) {
        if (error === 'cancel') return // 用户取消
        console.error('取消订单失败:', error)
        message.error('取消订单失败，请重试')
      }
    }

    onMounted(() => {
      fetchOrders()
    })

    return {
      loading,
      orders,
      filteredOrders,
      currentPage,
      totalPages,
      totalOrders,
      visiblePages,
      activeTab,
      tabs,
      changeTab,
      changePage,
      fetchOrders,
      getStatusText,
      getStatusClass,
      getTabLabel,
      canCancel,
      formatDate,
      formatPrice,
      goToOrderDetail,
      payOrder,
      confirmReceive,
      cancelOrder
    }
  }
}
</script>

<style scoped>
.order-list-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #ffffff;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.page-header h2 i {
  color: #00D4FF;
}

.order-filters {
  margin-bottom: 24px;
}

.filter-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 8px;
  gap: 4px;
}

.filter-tab {
  flex: 1;
  padding: 12px 16px;
  border: none;
  background: transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #B0BEC5;
  transition: all 0.3s ease;
}

.filter-tab:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.filter-tab.active {
  background: linear-gradient(45deg, #00D4FF, #4F46E5);
  color: white;
  box-shadow: 0 2px 8px rgba(0, 212, 255, 0.3);
}

.loading-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-skeleton {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 20px;
}

.skeleton-header,
.skeleton-content,
.skeleton-actions {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  animation: skeleton-loading 1.5s infinite ease-in-out;
}

.skeleton-header {
  height: 20px;
  width: 200px;
  margin-bottom: 12px;
}

.skeleton-content {
  height: 60px;
  width: 100%;
  margin-bottom: 12px;
}

.skeleton-actions {
  height: 16px;
  width: 150px;
}

@keyframes skeleton-loading {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
}

.empty-icon {
  font-size: 80px;
  color: #00D4FF;
  margin-bottom: 24px;
  opacity: 0.7;
}

.empty-state h3 {
  font-size: 24px;
  color: #ffffff;
  margin: 0 0 12px 0;
}

.empty-state p {
  font-size: 16px;
  color: #B0BEC5;
  margin: 0 0 32px 0;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.order-card:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 212, 255, 0.2);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-number {
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.order-date {
  font-size: 14px;
  color: #B0BEC5;
}

.order-status {
  display: flex;
  align-items: center;
}

.status-badge {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-pending {
  background: rgba(255, 193, 7, 0.2);
  color: #FFC107;
  border: 1px solid rgba(255, 193, 7, 0.3);
}

.status-paid {
  background: rgba(0, 212, 255, 0.2);
  color: #00D4FF;
  border: 1px solid rgba(0, 212, 255, 0.3);
}

.status-shipped {
  background: rgba(34, 197, 94, 0.2);
  color: #22C55E;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

.status-completed {
  background: rgba(59, 130, 246, 0.2);
  color: #3B82F6;
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.status-cancelled {
  background: rgba(239, 68, 68, 0.2);
  color: #EF4444;
  border: 1px solid rgba(239, 68, 68, 0.3);
}

.status-unknown {
  background: rgba(156, 163, 175, 0.2);
  color: #9CA3AF;
  border: 1px solid rgba(156, 163, 175, 0.3);
}

.order-content {
  padding: 20px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.order-content:hover {
  background: rgba(255, 255, 255, 0.05);
}

.order-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.summary-item i {
  width: 16px;
  color: #00D4FF;
}

.summary-item .label {
  color: #B0BEC5;
  font-weight: 500;
}

.summary-item .value {
  color: #ffffff;
  font-weight: 600;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.05);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-primary {
  background: linear-gradient(45deg, #00D4FF, #4F46E5);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: linear-gradient(45deg, #00B8E6, #3F3BE0);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0, 212, 255, 0.3);
}

.btn-success {
  background: linear-gradient(45deg, #22C55E, #16A34A);
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: linear-gradient(45deg, #16A34A, #15803D);
  transform: translateY(-1px);
}

.btn-danger {
  background: linear-gradient(45deg, #EF4444, #DC2626);
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: linear-gradient(45deg, #DC2626, #B91C1C);
  transform: translateY(-1px);
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #B0BEC5;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.btn-secondary:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.2);
  color: #ffffff;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 32px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  padding: 8px 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  color: #B0BEC5;
  transition: all 0.3s ease;
  min-width: 40px;
  text-align: center;
}

.page-btn:hover:not(:disabled) {
  border-color: #00D4FF;
  color: #00D4FF;
  background: rgba(0, 212, 255, 0.1);
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn.active {
  background: linear-gradient(45deg, #00D4FF, #4F46E5);
  color: white;
  border-color: transparent;
}

.pagination-info {
  font-size: 14px;
  color: #B0BEC5;
}

@media (max-width: 768px) {
  .container {
    padding: 12px;
  }
  
  .filter-tabs {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .filter-tab {
    flex: none;
    min-width: 80px;
  }
  
  .order-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .order-summary {
    grid-template-columns: 1fr;
  }
  
  .order-actions {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .pagination {
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style> 